import type { FunctionModel } from '../api/user/types'

/**
 * 转换后的路由项接口
 */
interface TransformedRouter {
  path: string
  name: string
  meta: {
    title: string
    auths?: string[]
    showLink?: boolean
    activePath?: string
  }
  children: TransformedRouter[]
  url?: string
  redirect?: string
}

/**
 * 内部使用的扩展路由接口
 */
interface InternalRouter extends TransformedRouter {
  id: number
  parentId: number
  hierarchy?: number
}

/**
 * 将扁平路由数组转换为父子嵌套结构
 *
 * @param routers 原始路由数组
 * @returns 转换后的嵌套路由结构
 */
export const transformRouters = (routers: FunctionModel[]): TransformedRouter[] => {
  // 创建ID映射表，方便快速查找
  const routerMap = new Map<number, InternalRouter>()
  // 创建结果数组，存放根级路由
  const result: InternalRouter[] = []
  // 存储按钮类型的路由
  const buttonRouters: FunctionModel[] = []
  // 初始映射表，先处理非按钮类型的路由
  routers.forEach(router => {

    if (router.actionName === 'workTable/todoTask/detail') {
      router.enfuncName = 'toxq';
    }
    // 如果是按钮类型，先存储起来，后续处理
    if (router.funcType === '2') {
      buttonRouters.push(router)
      return
    }
    // 创建新的路由对象
    const newRouter: InternalRouter = {
      id: router.resourceId ?? 0,
      parentId: router.parentId ?? 0,
      path: router.actionName ? `/${router.actionName}` : '',
      name: router.enfuncName
        ? router.enfuncName.replace(/[-/](\w)/g, (_, c) => c.toUpperCase())
        : '',
      meta: {
        title: router.funcName ?? '',
        showLink: (router?.hierarchy ?? 0) <= 3,
      },
      hierarchy: router.hierarchy ?? 0,
      children: [],
      url: router.url,
    }

    // 添加到映射表
    routerMap.set(router.resourceId ?? 0, newRouter)
  })

  // 处理按钮类型的路由，将其funcId添加到父节点的meta.auths中
  buttonRouters.forEach(buttonRouter => {
    const parent = routerMap.get(buttonRouter.parentId ?? 0)
    if (parent) {
      if (!parent.meta.auths) {
        parent.meta.auths = []
      }
      parent.meta.auths.push(buttonRouter.styleName?.toString() ?? '')
    }
  })

  // 构建嵌套结构
  routerMap.forEach(router => {
    // 添加到父节点的children中，如果parentId为-1表示是根节点
    if (router.parentId === -1) {
      result.push(router)
    } else {
      const parent = routerMap.get(router.parentId)
      if (parent) {
        parent.children.push(router)
      }
    }
  })

  // 递归查找第一个子路由的actionName和path
  function findFirstChildPath(
    router: InternalRouter,
    depth = 0,
  ): { actionName: string | null; path: string | null } {
    if (router.children.length === 0) {
      return { actionName: null, path: null }
    }

    // 先检查直接子路由
    for (const child of router.children) {
      if (child.path) {
        return {
          actionName: child.path.replace(/^\//, ''),
          path: child.path,
        }
      }
    }

    // 如果直接子路由没有path，递归查找
    for (const child of router.children) {
      const result = findFirstChildPath(child as InternalRouter, depth + 1)
      if (result.path) {
        return result
      }
    }

    return { actionName: null, path: null }
  }

  // 处理空path的情况，使用第一个子路由的actionName
  routerMap.forEach(router => {
    if (!router.path && router.children.length > 0) {
      const { actionName } = findFirstChildPath(router)
      if (actionName) {
        // 如果子路由的url也为空，则使用/p/p/前缀
        const hasEmptyUrlChild = router.children.some(child => !child.url)
        if (hasEmptyUrlChild) {
          router.path = `/p/p/${actionName}`
        } else {
          router.path = `/p/${actionName}`
        }
        // 更新name
        router.name = router.path.replace(/^\//, '').replace(/\.vue$/, '')
      }
    }
  })

  // 设置hierarchy > 3的路由的activePath
  routerMap.forEach(router => {
    const hierarchy = routers.find(r => r.resourceId === router.id)?.hierarchy ?? 0
    if (hierarchy > 3) {
      // 查找父路由
      const parent = routerMap.get(router.parentId)
      if (parent) {
        router.meta.activePath = parent.path
      }
    }
  })

  // 设置redirect属性
  routerMap.forEach(router => {
    if (!router.url && router.children.length > 0) {
      const { path } = findFirstChildPath(router)
      if (path) {
        router.redirect = path
      }
    }
  })

  /**
   * 清理内部路由对象，移除临时属性
   *
   * @param router 内部路由对象
   * @param level 路由级别，1表示顶级路由，2表示二级路由，以此类推
   * @returns 转换后的标准路由对象
   */
  function cleanRouter(router: InternalRouter, level = 1): TransformedRouter {
    const { id, parentId, ...rest } = router

    // 获取处理后的子路由，level+1 表示子路由的级别
    const processedChildren = router.children.map(child => {
      // 确保类型转换正确
      return cleanRouter(child as unknown as InternalRouter, level + 1)
    })

    // 如果子路由数组为空，则不添加children属性
    if (processedChildren.length === 0) {
      const { children, ...restWithoutChildren } = rest

      // 如果是一级或二级路由，删除name属性
      if (level <= 2) {
        const { name, ...restWithoutName } = restWithoutChildren
        return restWithoutName as TransformedRouter
      }

      return restWithoutChildren as TransformedRouter
    }

    // 如果是一级或二级路由，删除name属性
    if (level <= 2) {
      const { name, ...restWithoutName } = rest
      return {
        ...restWithoutName,
        children: processedChildren,
      } as TransformedRouter
    }

    return {
      ...rest,
      children: processedChildren,
    }
  }

  return result.map(root => cleanRouter(root))
}
